//
//  CreateOwnViewController.m
//  NotMadLibs
//
//  Created by ebeerman on 11/16/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "CreateOwnViewController.h"
#import "RootViewController.h"


@implementation CreateOwnViewController
@synthesize textField, inputtedTextExternal, inputtedTextInternal, tagTable, titleField;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        types = [[NSMutableDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"types" ofType:@"plist"]];
        typesArray = [types allKeys];
        [typesArray retain];
        [types retain];
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [textField setFont:[UIFont fontWithName:@"MarkerFelt-Thin" size:20.0]];
    textField.text = inputtedTextExternal;
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [types count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    NSString *imageName = @"table_cell";
    int imageSelect;
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    int row = indexPath.row;
    imageSelect = row%5 + 2;
    imageName = [imageName stringByAppendingFormat:@"%d.jpg", imageSelect];
    [cell.textLabel setFont:[UIFont fontWithName:@"MarkerFelt-Thin"
                                            size:20.0]];
    cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
    cell.textLabel.backgroundColor = [UIColor clearColor];
    cell.textLabel.text = [typesArray objectAtIndex:(row)];
  
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    int row = indexPath.row;
    NSString *externalTag = [NSString stringWithFormat:@" <%@>", [typesArray objectAtIndex:(row)]];
    self.textField.text = [self.textField.text stringByAppendingString:externalTag];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


-(IBAction)textDoneEditing:(id)sender{
    [textField resignFirstResponder];
    [titleField resignFirstResponder];
}

- (IBAction) submitClicked:(id)sender{
    BOOL alertBox = YES;
    NSString *word = self.titleField.text; 
    word = [word stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if ([word length] == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Input a title!" message:@"Please input a title!" delegate:self cancelButtonTitle:@"Ok, I will!" otherButtonTitles:nil];
        [alert show];
        [alert release];
        alertBox = NO;
    }
    else{
        word = self.textField.text;
        word = [word stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        if ([word length] == 0 && alertBox == YES) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Input a body!" message:@"Please input a body!" delegate:self cancelButtonTitle:@"Ok, I will!" otherButtonTitles:nil];
            [alert show];
            [alert release];
        }
    
        [self addToPassagesWithTitle:self.titleField.text andText:[self convertText:self.textField.text]];
    }
}

-(void)addToPassagesWithTitle:(NSString*) title andText:(NSString*) text {
    if ([text rangeOfString:@"<"].location == NSNotFound){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Input some tag!" message:@"Dude! You didn't even input a single tag!" delegate:self cancelButtonTitle:@"Oh darn, I'll add one!" otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
    else {
        NSMutableDictionary *newDictionary = [NSMutableDictionary dictionary];
        [newDictionary setValue:title forKey:@"file"];
        [newDictionary setValue:title forKey:@"title"];
        
        NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docDirectory = [documentPaths objectAtIndex:0];
        NSString *filename = [NSString stringWithFormat:@"%@/excerpts.plist", docDirectory];
        NSMutableArray *plist = [NSMutableArray arrayWithContentsOfFile:filename];
        [plist addObject:newDictionary];
        [plist writeToFile:filename atomically:YES];
        
        //code to create text file here
        filename = [NSString stringWithFormat:@"%@/%@.txt", docDirectory, title];
        [text writeToFile:filename atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(NSString*)convertText:(NSString*)text{
    NSArray *words = [text componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSArray *parsedWords = [NSArray array];
    NSString *word, *parsedWord;
    int count = 0;
    
    int wordCount = [words count];
    for (int i = 0; i < wordCount; i++){
        word = [words objectAtIndex:i];
        parsedWord = @"";
        for (int j = 0; j < [word length]; j++){
            NSString *achar = [NSString stringWithFormat:@"%c", [word characterAtIndex:j]];
            if ([achar isEqualToString:@">"]){
                parsedWord = [parsedWord stringByAppendingString:@"_"];
                parsedWord = [parsedWord stringByAppendingString:[NSString stringWithFormat:@"%d", count]];
                count++;
                parsedWord = [parsedWord stringByAppendingString:achar];
            }
            else{
                parsedWord = [parsedWord stringByAppendingString:achar];
            }
        }
        parsedWords = [parsedWords arrayByAddingObject:parsedWord];
    }
    
    return [parsedWords componentsJoinedByString:@" "];
}

@end
